package car.bkrc.com.car2018;

import android.Manifest;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.WindowManager;
import android.widget.Toast;

import com.bkrc.camera.XcApplication;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.ChecksumException;
import com.google.zxing.DecodeHintType;
import com.google.zxing.FormatException;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;
import com.hoho.android.usbserial.driver.UsbSerialDriver;
import com.hoho.android.usbserial.driver.UsbSerialPort;
import com.hoho.android.usbserial.driver.UsbSerialProber;
import com.hoho.android.usbserial.util.HexDump;
import com.hoho.android.usbserial.util.SerialInputOutputManager;
import com.luseen.luseenbottomnavigation.BottomNavigation.BottomNavigationItem;
import com.luseen.luseenbottomnavigation.BottomNavigation.BottomNavigationView;
import com.luseen.luseenbottomnavigation.BottomNavigation.OnBottomNavigationItemClickListener;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import car.bkrc.right.fragment.LeftFragment;
import car.bkrc.right.fragment.RightFragment1;
import car.bkrc.right.fragment.RightInfraredFragment;
import car.bkrc.right.fragment.RightOtherFragment;
import car.bkrc.right.fragment.RightZigbeeFragment;
import car2017_demo.FileService;
import car2017_demo.Global;
import car2017_demo.RGBLuminanceSource;
import car2017_demo.connect_transport;
import ui.bkrc.car.TitleToolbar;

public class FirstActivity extends AppCompatActivity {
    private ViewPager viewPager;
    private TitleToolbar mToolbar;  //工具栏
 //   private ActionBar mActionBar;  //ActionBar

    public static connect_transport Connect_Transport;
    // 小车ip
    public static String IPCar;
    // 摄像头IP
    public static String IPCamera = null;
    public static String purecameraip =null;
    public static boolean chief_status_flag = true;//主从状态
    public static boolean chief_control_flag = true; //主从控制
    public static boolean coded_control_flag = true; //角度、码盘控制

    private BottomNavigationView bottomNavigationView;
    public static Handler recvhandler =null;
     public static Handler but_handler;  //是按钮和menu同步

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams. FLAG_FULLSCREEN ,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_first1);
        but_handler =button_handler;  //用于leftfragment中隐藏的按钮和标题栏中的menu同步

        if(XcApplication.isserial == XcApplication.Mode.USB_SERIAL) {  //竞赛平台和a72通过usb转串口通信
            mHandler.sendEmptyMessageDelayed(MESSAGE_REFRESH, REFRESH_TIMEOUT_MILLIS); //启动usb的识别和获取
                Transparent.showLoadingMessage(this,"加载中",false);//启动旋转效果的对话框，实现usb的识别和获取
        }
        verifyStoragePermissions(this);   //加入用户是否可以使用内存

        mToolbar = (TitleToolbar) findViewById(R.id.toolbar);//使用标题栏
        setSupportActionBar(mToolbar);

        viewPager = (ViewPager) findViewById(R.id.viewpager);//使用viewPager实现页面滑动效果
        viewPager .setOffscreenPageLimit(3);

        //接下来与底部导航栏有关
        bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottomNavigation);

        int[] image = {R.drawable.ic_mic_black_24dp, R.drawable.ic_favorite_black_24dp,
                R.drawable.ic_book_black_24dp, R.drawable.github_circle};
        int[] color = {ContextCompat.getColor(this, R.color.firstColor), ContextCompat.getColor(this, R.color.secondColor),
                ContextCompat.getColor(this, R.color.thirdColor), ContextCompat.getColor(this, R.color.fourthColor)};
        if (bottomNavigationView != null) {
            bottomNavigationView.isWithText(false);
            // bottomNavigationView.activateTabletMode();
            bottomNavigationView.isColoredBackground(true);
            bottomNavigationView.setTextActiveSize(getResources().getDimension(R.dimen.text_active));
            bottomNavigationView.setTextInactiveSize(getResources().getDimension(R.dimen.text_inactive));
            bottomNavigationView.setItemActiveColorWithoutColoredBackground(ContextCompat.getColor(this, R.color.firstColor));
        }

        BottomNavigationItem bottomNavigationItem = new BottomNavigationItem
                ("主页", color[0], image[0]);
        BottomNavigationItem bottomNavigationItem1 = new BottomNavigationItem
                ("zigbee", color[1], image[1]);
        BottomNavigationItem bottomNavigationItem2 = new BottomNavigationItem
                ("红外", color[2], image[2]);
        BottomNavigationItem bottomNavigationItem3 = new BottomNavigationItem
                ("其他", color[3], image[3]);

        bottomNavigationView.addTab(bottomNavigationItem);
        bottomNavigationView.addTab(bottomNavigationItem1);
        bottomNavigationView.addTab(bottomNavigationItem2);
        bottomNavigationView.addTab(bottomNavigationItem3);

        bottomNavigationView.setOnBottomNavigationItemClickListener(new OnBottomNavigationItemClickListener() {
            @Override
            public void onNavigationItemClick(int index) {
                switch (index) {
                    case 0:
                        viewPager.setCurrentItem(0);
                        break;
                    case 1:
                        viewPager.setCurrentItem(1);
                        break;
                    case 2:
                        viewPager.setCurrentItem(2);
                        break;
                    case 3:
                        viewPager.setCurrentItem(3);
                        break;
                }
            }
        });
      Connect_Transport = new connect_transport(this,phHandler);        //实例化连接类
       setupViewPager(viewPager);  //加载fragment
    }

    private void setupViewPager(ViewPager viewPager) {
       ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFragment(RightFragment1.getInstance());
        adapter.addFragment(RightZigbeeFragment.getInstance());
        adapter.addFragment(RightInfraredFragment.getInstance());
        adapter.addFragment(RightOtherFragment.getInstance());
        viewPager.setAdapter(adapter);
    }


    private  Menu toolmenu ;
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {   //activity创建时创建菜单Menu
        getMenuInflater().inflate(R.menu.tool_rightitem, menu);
        toolmenu =menu;
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {  //菜单项监听
        int id = item.getItemId();
        Toast.makeText(FirstActivity.this,item.getTitle(),Toast.LENGTH_SHORT).show();
        switch (id)
        {
            case R.id.car_status:
                if(item.getTitle().equals("主车状态"))
                {
                    chief_status_flag =true;
                    item.setTitle(getResources().getText(R.string.follow_status));
                    Connect_Transport.vice(2);
                    LeftFragment.btchange_handler.obtainMessage(21).sendToTarget();
                }
                else if(item.getTitle().equals("从车状态"))
                {
                    chief_status_flag =false;
                    item.setTitle(getResources().getText(R.string.main_status));
                    Connect_Transport.vice(1);
                    LeftFragment.btchange_handler.obtainMessage(22).sendToTarget();
                }
                break;
            case R.id.car_control:
                if(item.getTitle().equals("主车控制"))
                {
                    chief_control_flag =true;
                    item.setTitle(getResources().getText(R.string.follow_control));
                    Connect_Transport.TYPE = 0xAA;
                    LeftFragment.btchange_handler.obtainMessage(23).sendToTarget();
                }
                else if(item.getTitle().equals("从车控制"))
                {
                    chief_control_flag =false;
                    item.setTitle(getResources().getText(R.string.main_control));
                    Connect_Transport.TYPE =  0x02;
                    LeftFragment.btchange_handler.obtainMessage(24).sendToTarget();
                }
                break;

            case R.id.angle_control:
                if(item.getTitle().equals("码盘控制"))
                {
                    coded_control_flag =true;
                    item.setTitle(getResources().getText(R.string.angle_control));
                    LeftFragment.btchange_handler.obtainMessage(25).sendToTarget();
                }
                else if(item.getTitle().equals("角度控制"))
                {
                    coded_control_flag =false;
                    item.setTitle(getResources().getText(R.string.coded_control));
                    LeftFragment.btchange_handler.obtainMessage(26).sendToTarget();
                }
                break;
            case R.id.clear_coded_disc:
                Connect_Transport.clear();
                break;
            case R.id.full_automatic:
                Toast.makeText(FirstActivity.this, "全自动", Toast.LENGTH_SHORT).show();
                break;
            case android.R.id.home:
                finish();
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

     private Handler button_handler =new Handler()  //实现menu和leftfragment中的三个按钮同步
    {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what)
            {
                case 11:
                    toolmenu.getItem(1).setTitle(getResources().getText(R.string.follow_status));
                    break;
                case 22:
                    toolmenu.getItem(1).setTitle(getResources().getText(R.string.main_status));
                    break;
                case 33:
                    toolmenu.getItem(2).setTitle(getResources().getText(R.string.follow_control));
                    break;
                case 44:
                    toolmenu.getItem(2).setTitle(getResources().getText(R.string.main_control));
                    break;
                case 55:
                    toolmenu.getItem(3).setTitle(getResources().getText(R.string.angle_control));
                    break;
                case 66:
                    toolmenu.getItem(3).setTitle(getResources().getText(R.string.coded_control));
                    break;
                default:
                    break;

            }
        }
    };



    //------------------------------------------------------------------------------------------
    //获取和实现usb转串口的通信，实现A72和竞赛平台的串口通信
    public static UsbSerialPort sPort = null;

    private final ExecutorService mExecutor = Executors.newSingleThreadExecutor();

    private SerialInputOutputManager mSerialIoManager;

    private final SerialInputOutputManager.Listener mListener =
            new SerialInputOutputManager.Listener() {

                @Override
                public void onRunError(Exception e) {
                    Log.e(TAG, "Runner stopped.");
                }

                @Override
                public void onNewData(final byte[] data) {   //新的数据
                    FirstActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Message msg =recvhandler.obtainMessage(1,data);
                            msg.sendToTarget();
                            FirstActivity.this.updateReceivedData(data);
                        }
                    });
                }
            };

    protected void controlusb() {
        Log.e(TAG, "Resumed, port=" + sPort);
        if (sPort == null) {
            Toast.makeText(FirstActivity.this,"No serial device.",Toast.LENGTH_SHORT).show();
        } else {
            openUsbDevice();
            if (connection == null) {
                mHandler.sendEmptyMessageDelayed(MESSAGE_REFRESH, REFRESH_TIMEOUT_MILLIS);
                Toast.makeText(FirstActivity.this,"Opening device failed",Toast.LENGTH_SHORT).show();
                return;
            }
            try {
                sPort.open(connection);
                sPort.setParameters(115200, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE);
            } catch (IOException e) {
                Toast.makeText(FirstActivity.this,"Error opening device: ",Toast.LENGTH_SHORT).show();
                try {
                    sPort.close();
                } catch (IOException e2) {
                }
                sPort = null;
                return;
            }
            Toast.makeText(FirstActivity.this,"Serial device: " + sPort.getClass().getSimpleName(),Toast.LENGTH_SHORT).show();
        }
        onDeviceStateChange();
        Transparent.dismiss();//关闭加载对话框
    }
    // 在打开usb设备前，弹出选择对话框，尝试获取usb权限
    private void openUsbDevice(){
        tryGetUsbPermission();

    }
//<<新权限测试》》
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};

    public static void verifyStoragePermissions(Activity activity) {
        // Check if we have write permission
        int permission = ActivityCompat.checkSelfPermission(activity,
                Manifest.permission.WRITE_EXTERNAL_STORAGE);

        if (permission != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE);
        }
    }

    private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
    private UsbDeviceConnection connection;

    private void tryGetUsbPermission(){

        IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
        registerReceiver(mUsbPermissionActionReceiver, filter);
        PendingIntent mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);

        //here do emulation to ask all connected usb device for permission
        for (final UsbDevice usbDevice : mUsbManager.getDeviceList().values()) {
            //add some conditional check if necessary
            if(mUsbManager.hasPermission(usbDevice)){
                //if has already got permission, just goto connect it
                //that means: user has choose yes for your previously popup window asking for grant perssion for this usb device
                //and also choose option: not ask again
                afterGetUsbPermission(usbDevice);
            }else{
                //this line will let android popup window, ask user whether to allow this app to have permission to operate this usb device
                mUsbManager.requestPermission(usbDevice, mPermissionIntent);
            }
        }
    }

    private void afterGetUsbPermission(UsbDevice usbDevice){

        Toast.makeText(FirstActivity.this, String.valueOf("Found USB device: VID=" + usbDevice.getVendorId() + " PID=" + usbDevice.getProductId()), Toast.LENGTH_LONG).show();
        doYourOpenUsbDevice(usbDevice);
    }

    private void doYourOpenUsbDevice(UsbDevice usbDevice){
        connection = mUsbManager.openDevice(usbDevice);
    }

    private final BroadcastReceiver mUsbPermissionActionReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (ACTION_USB_PERMISSION.equals(action)) {
                synchronized (this) {
                    UsbDevice usbDevice = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                    if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                        //user choose YES for your previously popup window asking for grant perssion for this usb device
                        if(null != usbDevice){
                            afterGetUsbPermission(usbDevice);
                        }
                    }
                    else {
                        //user choose NO for your previously popup window asking for grant perssion for this usb device
                        Toast.makeText(context, String.valueOf("Permission denied for device" + usbDevice), Toast.LENGTH_LONG).show();
                    }
                }
            }
        }
    };

    private void stopIoManager() {
        if (mSerialIoManager != null) {
            Log.e(TAG, "Stopping io manager ..");
            mSerialIoManager.stop();
            mSerialIoManager = null;
        }
    }

    private void startIoManager() {
        if (sPort != null) {
            Log.e(TAG, "Starting io manager ..");
            mSerialIoManager = new SerialInputOutputManager(sPort, mListener); //添加监听
            mExecutor.submit(mSerialIoManager); //在新的线程中监听串口的数据变化
        }
    }

    private void onDeviceStateChange() {
        stopIoManager();
        startIoManager();
    }

    private void updateReceivedData(byte[] data) {
        final String message = "Read " + data.length + " bytes: \n"
                + HexDump.dumpHexString(data) + "\n\n";
      //  Log.e("read data is ：：","   "+message);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(XcApplication.isserial == XcApplication.Mode.USB_SERIAL) {
            unregisterReceiver(mUsbPermissionActionReceiver);
            try {
                sPort.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            sPort = null;
        }
        else if(XcApplication.isserial == XcApplication.Mode.SOCKET) {
            Connect_Transport.destory();
        }
    }

    private static final int MESSAGE_REFRESH= 101;
    private static final long REFRESH_TIMEOUT_MILLIS = 5000;
    private UsbManager mUsbManager;
    private List<UsbSerialPort> mEntries = new ArrayList<UsbSerialPort>();
    private final String TAG = FirstActivity.class.getSimpleName();

    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MESSAGE_REFRESH:
                    refreshDeviceList();
                    break;
                default:
                    super.handleMessage(msg);
                    break;
            }
        }
    };

    private Handler usbHandler =new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if(msg.what ==2) {
                useUsbtoserial();
            }
        }
    };

    private void useUsbtoserial()
    {
        final UsbSerialPort port = mEntries.get(0);  //A72上只有一个 usb转串口，用position =0即可
        final UsbSerialDriver driver = port.getDriver();
        final UsbDevice device = driver.getDevice();
        final String usbid = String.format("Vendor %s  ，Product %s",
                HexDump.toHexString((short) device.getVendorId()),
                HexDump.toHexString((short) device.getProductId()));
        Message msg =LeftFragment.showidHandler.obtainMessage(22,usbid);
        msg.sendToTarget();
        FirstActivity.sPort = port;
        if(sPort !=null) {
            controlusb();  //使用usb功能
        }
    }

    private void refreshDeviceList() {
        mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
        new AsyncTask<Void, Void, List<UsbSerialPort>>() {
            @Override
            protected List<UsbSerialPort> doInBackground(Void... params) {
                Log.e(TAG, "Refreshing device list ...");
                Log.e("mUsbManager is :","  "+mUsbManager);
                final List<UsbSerialDriver> drivers =
                        UsbSerialProber.getDefaultProber().findAllDrivers(mUsbManager);

                final List<UsbSerialPort> result = new ArrayList<UsbSerialPort>();
                for (final UsbSerialDriver driver : drivers) {
                    final List<UsbSerialPort> ports = driver.getPorts();
                    Log.e(TAG, String.format("+ %s: %s port%s",
                            driver, Integer.valueOf(ports.size()), ports.size() == 1 ? "" : "s"));
                    result.addAll(ports);
                }
                return result;
            }

            @Override
            protected void onPostExecute(List<UsbSerialPort> result) {
                mEntries.clear();
                mEntries.addAll(result);
                usbHandler.sendEmptyMessage(2);
                Log.e(TAG, "Done refreshing, " + mEntries.size() + " entries found.");
            }
        }.execute((Void) null);
    }

    // 显示图片
    public  Handler phHandler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what==11){
                Toast.makeText(FirstActivity.this,Connect_Transport.openmv1_text, Toast.LENGTH_LONG).show();
            }
            //拍照保存
            if (msg.what==55){
                new FileService().savePhoto(LeftFragment.bitmap,
                        Global.PaiZhao + ".png");
                Toast.makeText(FirstActivity.this,"保存照片完成", Toast.LENGTH_LONG).show();
            }
            //识别指示灯颜色
            if (msg.what==44){
                color=getImagePixel(LeftFragment.bitmap);
                Connect_Transport.color=color;
                Toast.makeText(FirstActivity.this,color, Toast.LENGTH_LONG).show();
            }
            if (msg.what==100){
                String yy = "123";
                new FileService().savePhoto(LeftFragment.bitmap,
                        Global.ENCODE1 + ".png");
                Toast.makeText(FirstActivity.this,yy, Toast.LENGTH_LONG).show();
            }
            //单次扫描二维码
            if (msg.what == 181) {
                qrHandler.sendEmptyMessage(10);
                codeflag = true;
            }
            //多次扫描二维码
            if (msg.what==184){
                codeflag = true;
                qrHandler2.sendEmptyMessage(11);
            }
            //关闭--扫描二维码--线程
            if (msg.what==183){
                codeflag = false;
            }
            //扫描图形形状
            if (msg.what==180){
                shapeColor(LeftFragment.bitmap);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                Toast.makeText(FirstActivity.this,shapeColor+"=="+shapeResult, Toast.LENGTH_LONG).show();
            }
        };
    };
    private  boolean codeflag=true;  //用来判定 是否扫描到二维码，不是 就继续while
    private Timer timer;
    private String result_qr="0x03,0x05,0x14,0x45/0x67,0x34,0x78,0xA2";
    // 二维码、车牌处理(只识别一次)
    Handler qrHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 10:
                    timer = new Timer();
                    timer.schedule(new TimerTask() {
                        @Override
                        public void run() {
                            Result result = null;
                            RGBLuminanceSource rSource = new RGBLuminanceSource(
                                    LeftFragment.bitmap);
                            try {
                                BinaryBitmap binaryBitmap = new BinaryBitmap(
                                        new HybridBinarizer(rSource));
                                Map<DecodeHintType, String> hint = new HashMap<DecodeHintType, String>();
                                hint.put(DecodeHintType.CHARACTER_SET, "utf-8");
                                QRCodeReader reader = new QRCodeReader();
                                result = reader.decode(binaryBitmap, hint);
                                if (result.toString() != null) {
                                    result_qr = result.toString();
                                    timer.cancel();
                                    qrHandler.sendEmptyMessage(20);
                                }
                                System.out.println("正在识别");
                            } catch (NotFoundException e) {
                                e.printStackTrace();
                            } catch (ChecksumException e) {
                                e.printStackTrace();
                            } catch (FormatException e) {
                                e.printStackTrace();
                            }
                        }
                    }, 0, 200);
                    break;
                case 20:
                    Toast.makeText(FirstActivity.this, result_qr, Toast.LENGTH_LONG).show();
                    break;
                default:
                    break;
            }
        };
    };
    // 二维码、车牌处理(连续)
    Handler qrHandler2 = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 11:
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            while (codeflag) {
                                Result result = null;
                                RGBLuminanceSource rSource = new RGBLuminanceSource(
                                        LeftFragment.bitmap);
                                try {
                                    BinaryBitmap binaryBitmap = new BinaryBitmap(
                                            new HybridBinarizer(rSource));
                                    Map<DecodeHintType, String> hint = new HashMap<DecodeHintType, String>();
                                    hint.put(DecodeHintType.CHARACTER_SET, "utf-8");
                                    QRCodeReader reader = new QRCodeReader();
                                    result = reader.decode(binaryBitmap, hint);
                                    if (result.toString() != null) {
                                        result_qr = result.toString();
                                        Connect_Transport.result_qr=result_qr;              //将识别完成的二维码结果返回到全自动里面
                                        qrHandler2.sendEmptyMessage(12);
                                        Connect_Transport.encode1_flag=true;
                                        codeflag=false;
                                    }
                                    System.out.println("正在识别");
                                } catch (NotFoundException e) {
                                    e.printStackTrace();
                                } catch (ChecksumException e) {
                                    e.printStackTrace();
                                } catch (FormatException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }).start();
                    break;
                case 12:
                    Toast.makeText(FirstActivity.this, result_qr, Toast.LENGTH_LONG).show();
                    break;
            }
        }
    };

    public String color="黄色";
    //判断指示灯颜色
    public String getImagePixel(Bitmap bmap) {
        int[] rgb = new int[3];
        Bitmap bi = null;
        bi =bmap;

        int width = bi.getWidth();
        int height = bi.getHeight();
        int minx = 0;
        //int miny = bi.getMinY();
        int red = 0;
        int yello = 0;
        int green = 0;
        for (int i = minx; i < width; i+=5) {
            for (int j = height/3; j < height/1.5; j+=5) {
                int pixel = bi.getPixel(i, j);
                rgb[0] = (pixel & 0xff0000) >> 16;
                rgb[1] = (pixel & 0xff00) >> 8;
                rgb[2] = (pixel & 0xff);
                if(rgb[0]>=210&&rgb[1]<200&&rgb[2]<200)
                {
                    red++;
                }
                if(rgb[0]>=200&&rgb[1]>=200&&rgb[2]<200)
                {
                    yello++;
                }
                if(rgb[0]<=200&&rgb[1]>=200&&rgb[2]<200)
                {
                    green++;
                }
            }
        }
        if(red>yello)
        {
            if(red>green)
            {
                return "红色";
            }else
            {
                return "绿色";
            }
        }else
        {
            if(green>yello)
            {
                return "绿色";
            }else
            {
                return "黄色";
            }
        }
    }


    // 储存每个纵轴上的像素个数
    ArrayList<Integer> rlist = new ArrayList<Integer>();
    ArrayList<Integer> glist = new ArrayList<Integer>();
    ArrayList<Integer> ylist = new ArrayList<Integer>();
    private String shapeColor = "";  //识别颜色
    private String shapeResult = ""; //识别形状
    //形状识别
    private void shapeColor(Bitmap bmap) {
        // 得到图片的宽高
        int width = bmap.getWidth();
        int height = bmap.getHeight();
        rlist.clear();
        glist.clear();
        ylist.clear();
        shapeColor = "红色";
        shapeResult = "";
        // 横着检测
        for (int i = 0; i < width; i++) {
            // 黄色个数
            int yNum = 0;
            // 红绿各数
            int rNum = 0;
            int gNum = 0;
            for (int j = 0; j < height; j++) {
                // 得到图片上点（i，j）的像素
                int pixel = bmap.getPixel(i, j);
                int r = (pixel & 0xff0000) >> 16;
                int g = (pixel & 0xff00) >> 8;
                int b = (pixel & 0xff);
                // Log.e("yansezhi", "红色" + r + "    " + "绿色" + g + "蓝色" +
                // "    "
                // + b);
                // 红色
                if (r > 130 && g < 100 && b < 100)
                    rNum++;
                    // 红绿》》黄色
                else if (r > 130 && g > 130 && b < 100)
                    yNum++;
                    // 绿色
                else if (g > 130 && r < 100 && b < 100)
                    gNum++;

            }
            // 每行个数
            if (rNum > 10)
                rlist.add(rNum);
            if (gNum > 10)
                glist.add(gNum);
            if (yNum > 10)
                ylist.add(yNum);
            // Log.e("颜色个数：",rNum + "-----------" + gNum + "-----" + yNum);
        }
        int n = rlist.size();
        int m = glist.size();
        int j = ylist.size();
        if (shapeColor.equals("红色")) {
            if (n > 10)
                shape1(rlist.get(n / 2), rlist.get(n / 4),
                        rlist.get(n / 4 * 3), "红色");

            else
                shapeResult += "红色" + "矩形";
        }
        if (shapeColor.equals("绿色")) {
            if (m > 10)
                shape1(glist.get(m / 2), glist.get(m / 4),
                        glist.get(m / 4 * 3), "绿色");
            else
                shapeResult += "绿色" + "三角形";
        }
        if (shapeColor.equals("黄色")) {
            if (j > 10)
                shape1(ylist.get(j / 2), ylist.get(j / 4),
                        ylist.get(j / 4 * 3), "黄色");
            else
                shapeResult += "黄色" + "圆形";
        }
        Log.e("颜色行数：", rlist.size() + "-----------" + glist.size() + "-----"
                + ylist.size());

        String shapeResult_2 = shapeResult.substring(2, 3);  //将识别的颜色去除，保留形状。 圆
        Connect_Transport.shapeResult_3=shapeResult_2;   //将识别的指定颜色的形状传过去
    }
    // 一中间点为分界线，比较上下值到变化规律
    private void shape1(int n, int m, int j, String nameColor) {
        Log.e("图片中各个数：", "中间个数" + n + "上面个数" + m + "下面个数" + j);
        if (n > m + 30 && n > j + 30 || Math.abs(m - j) < 15)
            shapeResult += nameColor + "圆形";
        else if (n < m + 30 && n < j + 30 || Math.abs(n - m) < 15
                || Math.abs(n - j) < 15)

            shapeResult += nameColor + "矩形";
        else
            shapeResult += nameColor + "三角形";

    }
    private String content = "0x03,0x05,0x14,0x45/0x67,0x34,0x78,0xA2";
    private String opens = "";
    private String closes = "";
    private short[] openbyte;
    private short[] closesbyte;
    private void CRC16() {                                                    //从二维码图像识别保存的文件里，读出内容。
//        String[] names = content.split("/");
        String[] names = result_qr.split("/");
        String[] mbyte1 = names[0].split(",");
        String[] mbyte2 = names[1].split(",");
        for (int i = 0; i < mbyte1.length; i++) {
            opens += mbyte1[i].split("x")[1];
        }
        for (int j = 0; j < mbyte2.length; j++) {
            closes += mbyte2[j].split("x")[1];
        }
        openbyte = hexStringToBytes(opens);
        closesbyte = hexStringToBytes(closes);
        for (int i = 0; i < 4; i++) {
            Connect_Transport.openbyte[i] = (byte) openbyte[i];
            Connect_Transport.closesbyte[i] = (byte) closesbyte[i];
        }
        //计算出关键的效验码（报警器的开关）
        crc16Check(openbyte);
        Connect_Transport.openbyte[4] = CRCL;
        Connect_Transport.openbyte[5] = CRCH;
        crc16Check(closesbyte);
        Connect_Transport.closesbyte[4] = CRCL;
        Connect_Transport.closesbyte[5] = CRCH;

    }
    //字符串转换为short类型，以便wifi传输  String转byte    每两个数字前面加上0x
    private short[] hexStringToBytes(String hexString) {
        if (hexString == null || hexString.equals("")) {
            return null;
        }
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        short[] d = new short[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (short) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return d;
    }
    private short charToByte(char c) {
        return (short) "0123456789ABCDEF".indexOf(c);
    }
    //将二维码中关键的效验码转化成字符串保存。  byte转String  byte转String 以0xXX的形式转换
    private String toHexString(byte b) {
        String hex = Integer.toHexString(b & 0xff);
        hex = hex.toUpperCase();
        if (hex.length() == 1)
            hex = '0' + hex;
        return "0x" + hex;          //如果不想要0x可以 返回的时候删除0x
    }

    private int CRC_16_POLYNOMIALS = 0xA001;
    private byte CRCH;
    private byte CRCL;
    //计算效验码（报警器开关）
    private void crc16Check(short[] mbyte) {
        int CRC = 0xffff;
        for (int i = 0; i < mbyte.length; i++) {
            CRC = CRC ^ (mbyte[i]);
            for (int j = 0; j < 8; j++) {
                if ((CRC & 0x0001) == 1)
                    CRC = (CRC >> 1) ^ CRC_16_POLYNOMIALS;
                else
                    CRC = CRC >> 1;
            }
        }
        CRCL = (byte) CRC;
        CRCH = (byte) (CRC >> 8);

        try {
            //新建一个文件，用于保存二维码中关键的效验码.
            new FileService().saveToSDCard("CRC16.txt",
                    new FileService().read("CRC16.txt") + "算出的第一个校验码："
                            + toHexString(CRCL) + "算出的第二个校验码："
                            + toHexString(CRCH));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
    //显示输出内容的方法
    public  void XianShi(String str){
        Toast.makeText(FirstActivity.this, str, Toast.LENGTH_LONG).show();
    }

}
